<?php
namespace app\login\controller;

use app\XDeode;
use think\Controller;
use think\Db;

class Login extends Controller 
{
	public function index() 
	{
		return view('index');
	}
	/**
	 * 似乎是无用的接口， ping 表不存在
	 * @author 秋水
	 * @DateTime 2018-12-07T09:22:09+0800
	 */
	public function ping() 
	{
		$list = db('ping')->order('orderid asc')->select();
		$xcode = new XDeode(10,'6666.6666666');
		$zcode = new XDeode(10,'8888.8888888');
		$ccode = new XDeode(10,'9999.9999999');
		$arr['code'] = 1;
		$arr['key'] = $xcode->encode(time());
		$id = input('uid');
		if($id) 
		{
			$num = db('user')->where('id',$id)->count();
			if($num=='0') 
			{
				return json(['code'=>0,'msg'=>'用户不存在']);
			}
			db('user')->where('id',$id)->update(['key'=>$arr['key']]);
		}
		$arr['run'] = $id?$ccode->encode($id):'';
		foreach ($list as $key=>$value) 
		{
			unset($data);
			unset($file_path);
			unset($file_path);
			$list[$key]['id'] = $zcode->encode($value['id']);
			$file_path = iconv("UTF-8","gb2312",ROOT_PATH.'readtxt/'.$value['name'].'.txt');
			if(is_file($file_path)) 
			{
				$str = file_get_contents($file_path);
				if($str) 
				{
					$str_encoding = @mb_convert_encoding($str, 'UTF-8', 'UTF-8,GBK,GB2312,BIG5');
					$zarr = explode("\r\n", $str_encoding);
					$data= [];
					for ($i=0; $i < count($zarr);
					$i++) 
					{
						$data[] = explode('|',$zarr[$i]);
					}
					$list[$key]['count'] = count($data) - 1;
				}
				else 
				{
					$list[$key]['count']=0;
				}
				unset($data);
			}
			else 
			{
				$list[$key]['count'] = 0;
			}
		}
		$arr['list'] = $list;
		return json($arr);
	}

	/**
	 * 视频列表，分页展示
	 * @author 秋水
	 * @DateTime 2018-12-07T09:22:33+0800
	 */
	public function video() 
	{
		if(!input('page')) 
		{
			$page = 1;
		}
		else 
		{
			$page = input('page');
		}
		if(!input('limit')) 
		{
			$limit = 10;
		}
		else 
		{
			$limit = input('limit');
		}
		$list = db('video')->page($page)->limit($limit)->order('id desc')->select();
		if($list) 
		{
			$arr['code'] = 1;
			$arr['msg'] = $list;
		}
		else 
		{
			$arr['code'] = 0;
		}
		return json($arr);
	}

	/**
	 * 无用的接口，没有 audio 表
	 * @author 秋水
	 * @DateTime 2018-12-07T09:22:59+0800
	 */
	public function audio() 
	{
		if(!input('page')) 
		{
			$page = 1;
		}
		else 
		{
			$page = input('page');
		}
		if(!input('limit')) 
		{
			$limit = 10;
		}
		else 
		{
			$limit = input('limit');
		}
		$list = db('audio')->page($page)->limit($limit)->order('id desc')->select();
		if($list) 
		{
			$arr['code'] = 1;
			$arr['msg'] = $list;
		}
		else 
		{
			$arr['code'] = 0;
		}
		return json($arr);
	}

	/**
	 * 获取分享码
	 * @author 秋水
	 * @DateTime 2018-12-07T09:23:22+0800
	 */
	public function share() 
	{
		$id = input('uid');
		$uid = input('uid');
		$num = db('user')->where('id',$id)->count();
		if($num=='0') 
		{
			return json(['code'=>0,'msg'=>'用户不存在']);
		}
		header("Content-Type:text/html;charset=UTF-8");
		$host = 'http://www.xv3l.cn';
		$dwzapi = $host.'/app/index/qudao.html?uid='.base64_encode($id);
		if($num>0) 
		{
			$ip = $this->getIP();
			$ipnum = db('share')->where('ip',$ip)->count();
			if($ipnum=='0') 
			{
				db('user')->where('id',$uid)->setInc('sign');
				db('share')->insert(['uid'=>$uid,'ip'=>$ip]);
			}
			$data = db('user')->where('id',$uid)->find();
			if($data['power']=='2') 
			{
				$share_ma= db('user')->where('id',$data['parentid'])->value('share_ma');
			}
			else 
			{
				$share_ma= $data['share_ma'];
			}
		}
		else 
		{
			$share_ma= db('user')->where('power','0')->value('share_ma');
		}
		return json(['code'=>1,'msg'=>$dwzapi,'sign'=>advert('4'),'share'=>$share_ma]);
	}

	/**
	 * 获取banner列表
	 * @author 秋水
	 * @DateTime 2018-12-07T09:23:40+0800
	 */
	public function banner() 
	{
        $zad['zad1'] = advert('20');
		$num = db('banner')->select();
		if($num) 
		{
			$code= '1';
		}
		else 
		{
			$code= '0';
		}
		return json(['code'=>$code,'msg'=>$num]);
	}
  
  	/**
  	 * 无用的接口，没有fxlunbo表
  	 * @author 秋水
  	 * @DateTime 2018-12-07T09:24:18+0800
  	 */
  	public function fxlunbo() 
	{
		$num = db('fxlunbo')->select();
		if($num) 
		{
			$code= '1';
		}
		else 
		{
			$code= '0';
		}
		return json(['code'=>$code,'msg'=>$num]);
	}
  
  	/**
  	 * 获取播放记录
  	 * @author 秋水
  	 * @DateTime 2018-12-07T09:26:13+0800
  	 */
  	 public function newjilu() 
  {
    
    if(input('uid'))
    {
    	$where['uid']   =   input('uid');
    	$list	=	db('jilu')->where($where)->order('id desc')->select();
      	if($list)
        {
        	return json(['code'=>1,'msg'=>$list]);
        }else
        {
        	return json(['code'=>0,'msg'=>'什么也没有哦']);
        }
    }
   
  }

  /**
   * 新增播放记录
   * @author 秋水
   * @DateTime 2018-12-07T09:26:32+0800
   */
  public function jilu() 
    {
    	$data	=	input();
      	if($data){
          	$insert['uid']		=	$data['uid'];
          	$insert['title']	=	$data['title'];
          	$insert['url']		=	$data['url'];
          	$insert['time']		=	time();
            $insert['ping']		=	$data['ping'];
        	db('jilu')->insert($insert);
			return json(['code'=>1]);
        }
    
    }

    /**
     * 删除 用户uid 的所有 播放记录
     * @author 秋水
     * @DateTime 2018-12-07T09:26:43+0800
     */
  public function deljilu() 
  {
    
    if(input('uid'))
    {
    	$where['uid']   =   input('uid');
    	db('jilu')->where($where)->delete();
      	return json(['code'=>1]);
    }
   
  }

  /**
   * 获取电视台列表
   * @author 秋水
   * @DateTime 2018-12-07T09:27:17+0800
   */
  public function tvlist() 
	{
		$num = db('tv')->select();
		if($num) 
		{
			$code= '1';
		}
		else 
		{
			$code= '0';
		}
		return json(['code'=>$code,'msg'=>$num]);
    
	}
  	
  	/**
  	 * 获取电影列表
  	 * @author 秋水
  	 * @DateTime 2018-12-07T09:27:42+0800
  	 */
  public function vlist() 
	{
		$num = db('video')->select();
		if($num) 
		{
			$code= '1';
		}
		else 
		{
			$code= '0';
		}
		return json(['code'=>$code,'msg'=>$num]);
    
	}  
  
  	/**
  	 * 获取mn列表？mn是啥？？？
  	 * @author 秋水
  	 * @DateTime 2018-12-07T09:28:00+0800
  	 */
    public function mnlist() 
	{
		$num = db('mn')->select();
		if($num) 
		{
			$code= '1';
		}
		else 
		{
			$code= '0';
		}
		return json(['code'=>$code,'msg'=>$num]);
	}  

  	/**
  	 * 获取推荐列表
  	 * @author 秋水
  	 * @DateTime 2018-12-07T09:28:44+0800
  	 */
    public function tjlist() 
	{
		$num = db('tuijian')->select();
		if($num) 
		{
			$code= '1';
		}
		else 
		{
			$code= '0';
		}
		return json(['code'=>$code,'msg'=>$num]);
    
	}
  
  	/**
  	 * 获取直播列表
  	 * @author 秋水
  	 * @DateTime 2018-12-07T09:29:14+0800
  	 */
      public function zhibozb() 
	{
		$num = db('zhibo')->select();
		if($num) 
		{
			$code= '1';
		}
		else 
		{
			$code= '0';
		}
		return json(['code'=>$code,'msg'=>$num]);
    
	}
  
  	/**
  	 * 积分兑换会员时间
  	 * @author 秋水
  	 * @DateTime 2018-12-07T09:29:49+0800
  	 */
	public function exchange() 
	{
		$id = input('uid');
		$share = floor(input('share'));
		if($share%advert('4')!='0' || $share<=0) 
		{
			return json(['code'=>0,'msg'=>'消耗积分参数不正确']);
		}
		$data = db('user')->where('id',$id)->find();
		if(!$data) 
		{
			return json(['code'=>0,'msg'=>'用户不存在']);
		}
		if($data['power']=='0' or $data['type']=='1') 
		{
			return json(['code'=>0,'msg'=>'您已经是永久会员，兑换失败']);
		}
		else 
		{
			if($share>$data['sign']) 
			{
				return json(['code' => 0, 'msg' => '您的积分不够']);
			}
			else 
			{
				$oldshare = $data['sign'];
				$fen = $share/advert('4');
				$time = 60*60*24*$fen;
				$data = db('user')->where('id='.$id)->value('lasttime');
				if($data<time()) 
				{
					db('user')->where('id='.$id)->update(['lasttime'=>time()+$time]);
				}
				else 
				{
					db('user')->where('id='.$id)->update(['lasttime'=>$data+$time]);
				}
				db('user')->where('id='.$id)->update(['sign'=> $oldshare-$share]);
				return json(['code'=>1,'msg'=>'兑换成功','time'=>db('user')->where('id='.$id)->value('lasttime')]);
			}
		}
	}

	/**
	 * 登录验证 veify?应该是verify吧
	 * @author 秋水
	 * @DateTime 2018-12-07T09:31:00+0800
	 */
	public function veify() 
	{
		$data = input();
		$where['status'] = 1;
		$data = db('user')->where('username="'.$data['username'].'" and password ="'.md5(sha1($data['passwd'])).'" and status =1 and (power =1 or power=0 or power=3)')->find();
		if ($data) 
		{
			session('power', $data['power']);
			session('user', $data['id']);
			return json(['code' => '1']);
		}
		else 
		{
			return json(['code' => '0']);
		}
	}

	/**
	 * 设置支付密码
	 * @author 秋水
	 * @DateTime 2018-12-21T09:05:13+0800
	 */
	public function setPayPassword()
	{
		$uid = input('uid',0);
		$opassword = input('opassword','');
		$password = input('password','');

		$user = model('User')->where(['id'=>$uid])->find();
		// 用户是否存在
		if(!$user) {
			return json(['code'=>0,'msg'=>'用户不存在']);
		}

		// 旧密码是否正确
		if(!($user['pay_password'] == '' || $user['pay_password']==md5(md5($opassword)))) {
			return json(['code'=>0,'msg'=>'旧密码不正确']);
		}

		// 判断密码长度
		if(strlen($password) != 6) {
			return json(['code'=>0,'msg'=>'支付密码长度必须为6'.strlen($password)]);
		}

		$updateData = ['pay_password'=>md5(md5($password))];
		$r = model('User')->where(['id'=>$uid])->update($updateData);
		if($r !== false) {
			return json(['code'=>1,'msg'=>'设置成功']);
		} else {
			return json(['code'=>0,'msg'=>'设置失败']);
		}
	}

	/**
	 * 开通会员，加入分销树
	 * @author 秋水
	 * @DateTime 2018-12-10T15:33:45+0800
	 */
	public function userJoinVip()
	{
		$uid = input('uid',0);
		$password = input('password','');
		$user = model('User')->where(['id'=>$uid])->find();
		// 用户是否存在
		if(!$user) {
			return json(['code'=>0,'msg'=>'用户不存在']);
		}

		// 未设置支付密码
		if(empty($user['pay_password'])) {
			return json(['code'=>0,'msg'=>'未设置支付密码']);
		}

		// 支付密码是否正确
		if($user['pay_password'] != md5(md5($password))) {
			return json(['code'=>0,'msg'=>'支付密码不正确']);
		}

		// 加入树绑定过上下级
		$r = model('User')->joinTree($uid);

		// 更新积分和余额
		if($user['district_id'] > 0) {
			$district = model('District')->where(['id'=>$user['district_id']])->find();
			$totalCount = model('User')->where(['district_id'=>$user['district_id'],'isjoin'=>1])->count();
			$configData = model('TodoConfig')->getConfig();
			$pointRule = $configData['point_rule']['value'];
			$ruleArr = json_decode($pointRule, true);
			foreach ($ruleArr as $key => $o) {
				if($totalCount >= $o['min'] && $totalCount <= $o['max']) {
					// 本级应该获取到的积分
					$totalPoint = $totalCount*$o['point'];
					// 反馈到上级的积分
					$districtMng = model('User')->where(['id'=>$district['user_id']])->find();
					if($districtMng['district_id'] > 0) {
						// 如果代理的所属区不是系统默认区，就给所属区反馈积分
						$parentDistrict = model('District')->where(['id'=>$districtMng['district_id']])->find();
						$districtPointRate = $configData['district_point_rate']['value'];
						// 计算反馈的积分数
						$totalFeedbackPoint = $totalCount * $districtPointRate / 100;
						// 修改本级应获得积分
						$totalPoint = $totalPoint-$totalFeedbackPoint;
						// 给上级反馈积分
						$parentUpdateData = ['total_point'=>$parentDistrict['total_point']+$totalFeedbackPoint,'balance'=>$parentDistrict['balance']+$totalFeedbackPoint];
						model('District')->where(['id'=>$parentDistrict['id']])->update($parentUpdateData);
					}
					$addPoint = $totalPoint - $district['total_point'];
					if($addPoint > 0) {
						$updateData = ['total_point'=>$totalPoint,'balance'=>$district['balance']+$addPoint];
						model('District')->where(['id'=>$district['id']])->update($updateData);
					}
					break;
				}
			}
		}
		if($r['code'] != 1) {
			return json($r);
		} else {
			return json(['code'=>1,'msg'=>'成功开通会员']);
		}
	}

	/**
	 * 获取我的余额
	 * @author 秋水
	 * @DateTime 2018-12-28T16:42:50+0800
	 */
	public function myMoney()
	{
		$uid = input('uid', 0);

		$user = model('User')->where(['id'=>$uid])->find();
		// 用户是否存在
		if(!$user) {
			return json(['code'=>0,'msg'=>'用户不存在']);
		}

		return json(['code'=>1,'msg'=>'','data'=>$user]);
	}

	/**
	 * 积分详情
	 * @author 秋水
	 * @DateTime 2018-12-26T15:29:25+0800
	 */
	public function financeInfo()
	{
		$uid = input('uid', 0);

		$model = model('TodoFinance');
		$dataType1 = $model->field('sum(amount) as a')->where(['type'=>1,'uid'=>$uid])->find();
		$dataType2 = $model->field('sum(amount) as a')->where(['type'=>2,'uid'=>$uid])->find();
		$dataType3 = $model->field('sum(amount) as a')->where(['type'=>3,'uid'=>$uid])->find();
		$dataType4 = $model->field('sum(amount) as a')->where(['type'=>4,'uid'=>$uid])->find();
		$dataType5 = $model->field('sum(amount) as a')->where(['type'=>5,'uid'=>$uid])->find();

		$data = [
			'data_type_1' => $dataType1['a']?$dataType1['a']:0,
			'data_type_2' => $dataType2['a']?$dataType2['a']:0,
			'data_type_3' => $dataType3['a']?$dataType3['a']:0,
			'data_type_4' => $dataType4['a']?$dataType4['a']:0,
			'data_type_5' => $dataType5['a']?$dataType5['a']:0,
		];
		$totalIncome = number_format($data['data_type_1']+$data['data_type_2']+$data['data_type_3'],2);
		$data['total_income'] = $totalIncome;
		
		return json(['code'=>1,'msg'=>'','data'=>$data]);
	}

	/**
	 * 获取我的团队信息
	 * @author 秋水
	 * @DateTime 2018-12-28T21:56:03+0800
	 */
	public function teamInfo()
	{
		$uid = input('uid', 0);

		$model = model('User');
		$user = $model->where(['id'=>$uid])->find();
		if(!$user) {
			return json(['code'=>1,'msg'=>'用户不存在']);
		}
		$childrencount = $user['childrencount'];
		$directcount = $user['directcount'];
		$assistcount = $childrencount-$directcount;

		return json(['code'=>1,'msg'=>'','data'=>[
			'childrencount' => $childrencount,
			'directcount' => $directcount,
			'assistcount' => $assistcount,
		]]);
	}

	/**
	 * 获取积分日志
	 * @author 秋水
	 * @DateTime 2018-12-26T16:24:37+0800
	 */
	public function financeDetails()
	{
		$uid = input('uid', 0);
		$type = input('type', 0);

		$model = model('TodoFinance');
		$list = $model->where(['uid'=>$uid,'type'=>$type])->order('changetime desc')->select();

		foreach ($list as $key => $o) {
			$list[$key]['ctime'] = date('Y-m-d H:i', $o['changetime']);
		}

		return json(['code'=>1,'msg'=>'','data'=>$list]);
	}

	/**
	 * 提现记录
	 * @author 秋水
	 * @DateTime 2018-12-31T19:11:29+0800
	 */
	public function cashList()
	{
		$uid = input('uid', 0);
		$list = model('Cash')->where(['uid'=>$uid])->order('create_time desc')->select();
		$totalCash = model('Cash')->where(['uid'=>$uid,'status'=>2])->field('sum(money) as amount')->find();

		$amount = $totalCash['amount']?$totalCash['amount']:0;
		return json(['code'=>1,'msg'=>'','data'=>['list'=>$list,'amount'=>$amount]]);
	}

	/**
	 * 赠送积分
	 * @author 秋水
	 * @DateTime 2018-12-18T21:35:40+0800
	 */
	public function sendMoney()
	{
		$uid = input('uid', 0);
		$password = input('password','');
		$touid = input('touid', 0);
		$money = input('money', 0);

		if($uid == $touid) {
			return json(['code'=>0,'msg'=>'不能转让给自己']);
		}

		if(!$money > 0) {
			return json(['code'=>0,'msg'=>'金额必须大于0']);
		}
		$user = model('User')->where(['id'=>$uid])->find();
		$touser = model('User')->where(['id'=>$touid])->find();
		// 用户是否存在
		if(!$user || !$touser) {
			return json(['code'=>0,'msg'=>'用户不存在']);
		}

		// 未设置支付密码
		if(empty($user['pay_password'])) {
			return json(['code'=>0,'msg'=>'未设置支付密码']);
		}

		if($password == '') {
			return json(['code'=>0,'msg'=>'请输入支付密码，或更新到最新版APP']);
			// return json(['code'=>0,'msg'=>'请输入支付密码']);
		}

		// 支付密码是否正确
		if($user['pay_password'] != md5(md5($password))) {
			return json(['code'=>0,'msg'=>'支付密码不正确']);
		}

		// 余额是否充足
		if($user['money'] < $money) {
			return json(['code'=>0,'msg'=>'余额不足']);
		}

		Db::startTrans();
		try{
			$r = model('User')->where(['id'=>$uid])->setDec('money', $money);
			if($r !== false) {
				// 扣款成功才给对方打款
				$r = model('User')->where(['id'=>$touid])->setInc('money', $money);
				if($r == false) {
					Db::rollback();
					return json(['code'=>0,'msg'=>'赠送失败']);
				}
			} else {
				Db::rollback();
				return json(['code'=>0,'msg'=>'扣款失败']);
			}

			// 记录日志
			$logData = [
				'uid' => $uid,
				'touid' => $touid,
				'amount' => $money,
				'type' => 4,
				'changetime' => time()
			];
			model('TodoFinance')->insert($logData);

			$logData = [
				'uid' => $touid,
				'touid' => $uid,
				'amount' => $money,
				'type' => 5,
				'changetime' => time()
			];
			model('TodoFinance')->insert($logData);
			Db::commit();
		} catch(Explode $e){
			Db::rollback();
			return json(['code'=>0,'msg'=>$e->getMessage]);
		}
		$user = model('User')->where(['id'=>$uid])->find();
		return json(['code'=>1,'msg'=>'赠送成功','data'=>$user]);
	}

	/**
	 * 充值积分
	 * @author 秋水
	 * @DateTime 2018-12-27T21:19:55+0800
	 */
	public function recharge()
	{
		$uid = input('uid', 0);
		$money = input('money', 0);
		$type = input('type', 'wxpay');

		if(!$money > 0) {
			return json(['code'=>0,'msg'=>'金额必须大于0']);
		}
		$user = model('User')->where(['id'=>$uid])->find();
		if(!$user) {
			return json(['code'=>0,'msg'=>'用户不存在']);
		}

		$payOrderData = [
			'uid' => $uid,
			'money' => $money,
			'status' => 1,
			'create_time' => time()
		];

		$id = model('PayOrder')->insertGetId($payOrderData);
		$orderNumber = 1000000000+$id;
		$r = model('PayOrder')->where(['id'=>$id])->update(['order_number'=>$orderNumber]);
		if($type == 'wxpay') {
			$notify_url = request()->domain().'/login/wxpay/apppaysucess';
			$wxpay_controller = new Wxpay();
			$pay_result = $wxpay_controller->unifiedorder('积分充值',$orderNumber,$money,$notify_url);
			if($pay_result['code'] == 1) {
				return json(['code'=>1,'msg'=>'','data'=>$pay_result,'order_number'=>$orderNumber]);
			} else {
				return json(['code'=>0,'msg'=>'支付失败','data'=>$pay_result]);
			}
		}
	}

	/**
	 * 支付成功后修改支付状态
	 * @author 秋水
	 * @DateTime 2019-01-08T11:35:18+0800
	 */
	public function rechargeSuccess()
	{
		$order_number = input('order_number', '');
		$uid = input('uid', 0);

		$order = model('PayOrder')->where(['order_number'=>$order_number,'uid'=>$uid])->find();

		if(!$order) {
			return json(['code'=>0,'msg'=>'订单不存在']);
		}

		if($order['status']==2) {
			return json(['code'=>0,'msg'=>'订单已支付']);
		}

		if($order['status']==3) {
			return json(['code'=>0,'msg'=>'订单已取消']);
		}

		Db::startTrans();
		try{
			$r = model('PayOrder')->where(['order_number'=>$order_number,'uid'=>$uid,'status'=>1])->update(['status'=>2]);
			if(!$r) {
				Db::rollback();
				return json(['code'=>0,'msg'=>'支付失败']);
			}
			$r = model('User')->where(['id'=>$uid])->setInc('money',$order['money']);

			if(!$r) {
				Db::rollback();
				return json(['code'=>0,'msg'=>'支付失败']);
			}
			Db::commit();
			return json(['code'=>1,'msg'=>'支付成功']);
		} catch(Explode $e){
			Db::rollback();
			return json(['code'=>0,'msg'=>$e->getMessage]);
		}
	}

	/**
	 * 提现申请
	 * @author 秋水
	 * @DateTime 2018-12-19T14:08:06+0800
	 */
	public function cash()
	{
		$uid = input('uid', 0);
		$type = input('type', '');
		$money = input('money', 0);

		// 判断用户是否存在
		$user = model('User')->where(['id'=>$uid])->find();
		if(!$user) {
			return json(['code'=>0,'msg'=>'用户不存在']);
		}
		$userAuth = model('UserAuth')->where(['uid'=>$uid])->find();
		if(!$userAuth) {
			return json(['code'=>2,'msg'=>'没有设置提现信息']);
		}

		$todoConfig = model('TodoConfig')->getConfig();
		$cashmutiple = $todoConfig['cashmultiple']['value'];
		// 金额必须是 配置 的倍数，如果不足 配置倍数最低数，就提示错误
		$money = floor($money/$cashmutiple)*$cashmutiple;
		if(!$money > 0) {
			return json(['code'=>0,'msg'=>'提现金额错误']);
		}

		if($money > $user['money']) {
			return json(['code'=>0,'msg'=>'余额不足']);
		}
		// if($money > $user['cashamount']) {
		// 	return json(['code'=>0,'msg'=>'可兑换余额不足']);
		// }

		Db::startTrans();
		try{
			$cashData = [
				'uid' => $uid,
				'money' => $money,
				'type' => $type,
				'create_time' => time(),
				'status' => 1,
			];
			$r = model('Cash')->insert($cashData);
			if(!$r) {
				Db::rollback();
				return json(['code'=>0,'msg'=>'插入数据失败']);
			}
			$updateData = [
				'money'=>$user['money']-$money,
				// 'cashamount' => $user['cashamount']-$money,
			];
			$r = model("User")->where(['id'=>$uid])->update($updateData);
			if($r === false) {
				Db::rollback();
				return json(['code'=>0,'msg'=>'扣款失败']);
			}
			Db::commit();
		} catch(Explode $e){
			Db::rollback();
			return json(['code'=>0,'msg'=>$e->getMessage]);
		}
		return json(['code'=>1,'msg'=>'提现申请成功','data'=>['money'=>($user['money']-$money)]]);
	}

	/**
	 * 个人认证提交
	 * @author 秋水
	 * @DateTime 2018-12-28T11:25:20+0800
	 */
	public function UserAuth()
	{
		$uid = input('uid', 0);
		$ali_name = input('ali_name', '');
		$ali_account = input('ali_account', '');
		$wx_img = input('wx_img', '');
		$bank_card_name = input('bank_card_name', '');
		$bank_card_number = input('bank_card_number', '');
		$bank_name = input('bank_name', '');
		$mobile = input('mobile', '');

		$updateData = [
			'uid' => $uid,
			'ali_name' => $ali_name,
			'ali_account' => $ali_account,
			'wx_img' => $wx_img,
			'bank_card_name' => $bank_card_name,
			'bank_card_number' => $bank_card_number,
			'bank_name' => $bank_name,
			'mobile' => $mobile,
			'status' => 1,
			'create_time' => time(),
		];

		$existData = model('UserAuth')->where(['uid'=>$uid])->find();
		if($existData) {
			$r = model('UserAuth')->where(['uid'=>$uid])->update($updateData);
		} else {
			$r = model("UserAuth")->insert($updateData);
		}

		if($r !== false) {
			return json(['code'=>1,'msg'=>'提交成功','data'=>$wx_img]);
		} else {
			return json(['code'=>0,'msg'=>'提交失败']);
		}
	}

	/**
	 * 获取我的提现账号信息
	 * @author 秋水
	 * @DateTime 2018-12-30T08:45:29+0800
	 */
	public function myUserAuth()
	{
		$uid = input('uid', 0);

		$userAuth = model('UserAuth')->where(['uid'=>$uid])->find();
		if(empty($userAuth['wx_img'])) {
			$userAuth['wx_img'] = '/public/static/assets/images/wxcash.png';
		}
		if(!$userAuth) {
			return json(['code'=>0,'msg'=>'无有效信息']);
		} else {
			return json(['code'=>1,'msg'=>'','data'=>$userAuth]);
		}
	}

	/**
	 * 客服微信二维码
	 * @author 秋水
	 * @DateTime 2018-12-29T17:54:03+0800
	 * @return   [type]                   [description]
	 */
	public function serverImg()
	{
		$todoConfig = model('TodoConfig')->getConfig();
		$serverImg = request()->domain().$todoConfig['server_img']['value'];
		$serverWx = $todoConfig['server_wx']['value'];
		echo '<body style="margin:20px 0;"><div style="width:300px; max-height:300px; text-align:center;"><img style="width:80%" src="'.$serverImg.'"></div><div style="width:300px; text-align:center;"><span style="font-size:20px;">'.$serverWx.'</span></div></body>';
	}

	// 测试方法
	public function todotest()
	{
		$todoConfig = model('TodoConfig')->getConfig();
		$vipPrice = $todoConfig['platform']['value']
			+$todoConfig['directfee']['value']
			+$todoConfig['undirectfee']['value']*$todoConfig['level']['value'];
		var_dump($vipPrice);

	}

	/**
	 * 获取文章列表
	 * @author 秋水
	 * @DateTime 2018-12-29T09:05:58+0800
	 */
	public function questionList()
	{
		$list = db('article')->where(['type'=>1,'status'=>1])->order('sort desc')->select();
		return json(['code'=>1,'msg'=>'','data'=>['count'=>count($list),'list'=>$list]]);
	}

	/**
	 * 获取问题内容
	 * @author 秋水
	 * @DateTime 2019-02-20T17:14:02+0800
	 */
	public function getQuestion()
	{
		$id = input('id', 0);
		$article = db('article')->where(['id'=>$id])->find();

		$article['content'] = str_replace('src="/', 'src="'.request()->domain().'/', $article['content']);

		return json(['code'=>1,'data'=>$article]);
	}

	/**
	 * 获取客服电话
	 * @author 秋水
	 * @DateTime 2018-12-29T09:59:58+0800
	 */
	public function servertel()
	{
		$todoConfig = model('TodoConfig')->getConfig();
		$servertel = $todoConfig['servertel']['value'];
		return json(['code'=>1,'msg'=>'','data'=>$servertel]);
	}

	/**
	 * 卡密兑换会员
	 * @author 秋水
	 * @DateTime 2018-12-07T09:31:20+0800
	 */
	public function dianka() 
	{
		$data = input();
		if(!empty($data['uid']) && !empty($data['dianka'])) 
		{
			// $num = model('User')->where('id',$data['uid'])->count();
			
			$dianka = db('dianka')->where('dianka',$data['dianka'])->find();
			if(!$dianka) 
			{
				return json(['code'=>0,'msg'=>'卡号错误']);
			}
			if($dianka['y']=='1') 
			{
				return json(['code'=>0,'msg'=>'点卡已使用']);
			}
			$user = model('User')->where('id',$data['uid'])->find();
			if(!$user) 
			{
				return json(['code'=>0,'msg'=>'用户不存在']);
			}
			$parentUser = model('User')->where('id',$user['parentid'])->find();
			// 判断邀请码是否在允许的邀请码中
			$enableCodes = model('TodoConfig')->where('title','enable_codes')->find();
			$enableCodesArr = explode(',', $enableCodes['value']);
			if(!in_array($parentUser['share_ma'], $enableCodesArr)) {
				return json(['code'=>0,'msg'=>'邀请码填写错误，激活失败。请重新注册，按要求填入邀请码']);
			}
			// if($user['power']=='0' || $user['type']=='1') 
			// {
			// 	return json(['code'=>0,'msg'=>'您已是永久会员']);
			// }
			// 购买记录修改状态，废弃
			// $where['kami'] = $data['dianka'];
			// $ztai = db('pay')->where($where)->find();
			// if($ztai) 
			// {
			// 	db('pay')->where('kami',$data['dianka'])->update(['cid'=>$data['uid']]);
			// }
			// else 
			// {
			// }
			// if($dianka['type']=='1') 
			// {
			// 	// 永久点卡
			// 	db('user')->where('id',$data['uid'])->update(['type'=>'1']);
			// 	db('dianka')->where('dianka',$data['dianka'])->update(['y'=>'1','yid'=>$data['uid'],'stime'=>time()]);
			// 	$lasttime = '-1';
			// }
			// else 
			// {
				if($user['lasttime']>time()) 
				{
					$lasttime = $user['lasttime'] + $dianka['time'];
				}
				else 
				{
					$lasttime = time() + $dianka['time'];
				}
				model('User')->where('id',$data['uid'])->update(['lasttime'=>$lasttime,'isjoin'=>2]);
				db('dianka')->where('dianka',$data['dianka'])->update(['y'=>'1','yid'=>$data['uid'],'stime'=>time()]);
				$lasttime = model('User')->where('id',$data['uid'])->value('lasttime');
			// }
			// 给上级返利
			$todoConfig = model('TodoConfig')->getConfig();
			model('User')->where(['id'=>$user['parentid']])->setInc('money',$todoConfig['code_point']['value']);
			// 记录日志
			$logData = [
				'uid' => $user['parentid'],
				'amount' => $todoConfig['code_point']['value'],
				'type' => 1,
				'changetime' => time()
			];
			$todoFinanceModel = model('TodoFinance');
			$todoFinanceModel->insert($logData);
			
			return json(['code' => '1','msg'=>'充值成功','lasttime'=>$lasttime]);
		}
		else 
		{
			return json(['code' => '0','msg'=>'参数缺失']);
		}
	}

	/**
	 * 获取客户端IP
	 * @author 秋水
	 * @DateTime 2018-12-07T09:31:49+0800
	 */
	function getIP() 
	{
		if (getenv('HTTP_CLIENT_IP')) 
		{
			$ip = getenv('HTTP_CLIENT_IP');
		}
		elseif (getenv('HTTP_X_FORWARDED_FOR')) 
		{
			$ip = getenv('HTTP_X_FORWARDED_FOR');
		}
		elseif (getenv('HTTP_X_FORWARDED')) 
		{
			$ip = getenv('HTTP_X_FORWARDED');
		}
		elseif (getenv('HTTP_FORWARDED_FOR')) 
		{
			$ip = getenv('HTTP_FORWARDED_FOR');
		}
		elseif (getenv('HTTP_FORWARDED')) 
		{
			$ip = getenv('HTTP_FORWARDED');
		}
		else 
		{
			$ip = $_SERVER['REMOTE_ADDR'];
		}
		return $ip;
	}
  
  	public function zce() 
    {
    	$data = input();
        $insert['phone'] = $data['phone'];
		$insert['sid'] = $data['sid'];
		$insert['uid'] = $data['uid'];
     	$insert['code'] = $data['code'];
     	$count = db('zce')->where('phone',$data['phone'])->count();
    	if($count>0)
        {
          return jsonp(['code'=>0,'msg'=>'手机号码已领取，请下载APP查看']);
          
        }else
        {
        	db('zce')->insert($insert);
          	return jsonp(['code'=>1]);
        }
    }
  
  
  	/**
  	 * 支付
  	 * @author 秋水
  	 * @DateTime 2018-12-07T10:01:55+0800
  	 */
	public function pay() 
	{
		$data = input();

		$insert['outtrade'] = $data['outtrade'];
		$insert['trade'] = $data['trade'];
		$insert['type'] = $data['type'];
		$insert['money'] = $data['money'];
		$insert['trade_status'] = $data['trade_status'];
		$insert['name'] = $data['name'];
		$insert['time'] = time();

		$where['outtrade'] = $data['outtrade'];
		if($where) 
		{
			$ztai = db('pay')->where($where)->find();
			if($ztai['outtrade'] == $data['outtrade']) 
			{
				return json(['code'=>1,'msg'=>$ztai['kami']]);
			}
		}
		else 
		{
		}
		if($data['money']=='1.5'||$data['money']=='3'||$data['money']=='9'||$data['money']=='18'||$data['money']=='36'||$data['money']=='299') 
		{
		}
		else 
		{
			return json(['code'=>1,'msg'=>'订单支付金额有误，请联系客服处理']);
		}
		if($data['trade_status']!='TRADE_SUCCESS') 
		{
			return json(['code'=>0,'msg'=>'支付未完成']);
		}
		if($data['money']=='1.5') 
		{
			$ctime = 0.75;
		}
		if($data['money']=='3') 
		{
			$ctime = 1.5;
		}
		if($data['money']=='9') 
		{
			$ctime = 4.5;
		}
       if($data['money']=='18') 
		{
			$ctime = 9;
		} 
       if($data['money']=='36') 
		{
			$ctime = 18;
		}            
		if($data['money']=='299') 
		{
			$ctime = 150;
		}
		$type = '0';
		switch ($ctime) 
		{
			case 0.75;
			$time = 7*60*60*24;
			$name = '七天';
			break;
			case 1.5;
			$time = 30*60*60*24;
			$name = '一个月';
			break;
			case 4.5;
			$time = 90*60*60*24;
			$name = '三个月';
			break;
			case 9;
			$time = 180*60*60*24;
			$name = '六个月';
			break;            
			case 18;
			$time = 365*60*60*24;
			$name = '一年';
			break;
			case 150;
			$type = 1;
			$time = 0;
			$name = '永久';
			break;
		}
		$kami = randstring(15);
		$jiaka['uid'] = 1;
		$jiaka['dianka'] = $kami;
		$jiaka['ctime'] = time();
		$jiaka['y'] = 0;
		$jiaka['yid'] = '';
		$jiaka['time'] = $time;
		$jiaka['type'] = $type;
		$jiaka['name'] = $name;
		if($data) 
		{
			$insert['kami'] = $kami;
			db('pay')->insert($insert);
		}
		db('dianka')->insert($jiaka);
		return json(['code'=>1,'msg'=>$kami]);
	}
  
  	/**
  	 * 统计用户信息
  	 * @author 秋水
  	 * @DateTime 2018-12-07T10:21:22+0800
  	 */
  	public function tongji() 
    {
    	$data	=	input();
      	if($data){
          	$insert['os']	=	$data['os'];
          	$insert['imei']	=	$data['imei'];
          	$insert['uid']	=	$data['uid'];
          	$insert['time']	=	time();
        	db('tongji')->insert($insert);
			return json(['code'=>1]);
        }
    }

    /**
     * 注册
     * @author 秋水
     * @DateTime 2018-12-07T10:21:49+0800
     */
	public function create() 
	{
		$data = input();
		$where['ip'] = $this->getIP();
		$where['day'] = date('Y-m-d');
		$select = db('count')->where($where)->value('count');
		// if($select>=5) 
		// {
		// 	return json(['code'=>0,'msg'=>'注册数量超过当天限制']);
		// }
      
      	// 分享码直接由提交获得
      	// $zce['phone'] = $data['name'];
      	// $ztai = db('zce')->where($zce)->find();
      	
      	// if($ztai)
       //  {
       //    $data['share_ma'] = $ztai['code'];
       //  }else
       //  {
       //    $data['share_ma'] = '000001';
       //  }
      	

		$parent = db('user')->where('share_ma',$data['share_ma'])->find();
		if(!$parent) 
		{
			// 如果没有分享码就注册失败
			return json(['code'=>0,'msg'=>'注册失败,请填写正确邀请码']);
			// $pid = 1;
		} else {
			if($parent['parentid'] == 0) {
				$treeid = $parent['id'];
			} else {
				$treeid = $parent['treeid'];
			}
		}

		// 一个手机号最多注册三个账号
		$mobileUserCount = db('user')->where('phone',$data['phone'])->count();
		if($mobileUserCount > 2) {
			return json(['code'=>0,'msg'=>'该手机号账号已满三个，不能再注册了']);
		}
		$parentid = $parent['id'];
		$insert['phone'] = $data['phone'];
		$insert['username'] = $data['username'];
		$insert['password'] = md5(sha1($data['password']));
		$insert['pay_password'] = md5(md5('123456'));
		$insert['power'] = '2';
		$insert['status'] = '1';
		$insert['parentid'] = $parentid;
		$insert['treeid'] = $treeid;
		$insert['ctime'] = time();
		$insert['logintime'] = '0';
		$insert['lasttime'] = time();
		$insert['money'] = '0.00';
		$insert['is_district_mng'] = 0;

		// 分区信息
		if($parent['is_district_mng'] > 0) {
			// 上级是区长
			$district = model('District')->where(['user_id'=>$parent['id']])->find();
			$insert['district_id'] = $district['id'];
		} else if($parent['is_district_mng'] == 0) {
			// 上级不是区长
			$insert['district_id'] = $parent['district_id'];
		}
		$count = db('user')->where('username',$data['username'])->count();
		if($count>0) 
		{
			return json(['code'=>0,'msg'=>'账户已存在']);
		}
		$id = db('user')->insertGetId($insert);
		if($id > 0) 
		{
			$share_ma = dechex($id+1048576); // 将id转化为六位十六进制
			db('user')->where(['id'=>$id])->update(['share_ma'=>$share_ma]);
			if($select=='') 
			{
				db('count')->insert([ 'day' => date('Y-m-d'), 'count' => 1, 'ip' => $this->getIP() ]);
			}
			else if($select=='1') 
			{
				db('count')->where('ip="'.$this->getIP().'" and day="'.date('Y-m-d').'"')->update([ 'count' => 2, ]);
			}
			$user = db('user')->where(['id'=>$id])->find();
			return json(['code'=>1,'msg'=>$user]);
		}
		else 
		{
			return json(['code'=>0,'msg'=>'注册失败']);
		}
		;
	}

	/**
	 * 获取用户信息
	 * @author 秋水
	 * @DateTime 2019-01-09T18:56:12+0800
	 */
	public function getUserData()
	{
		$data = input();
		$where['id'] = $data['uid'];
		$user = db('user')->where($where)->find();
		if($user) {
			return json(['code'=>1, 'data'=>$user]);
		} else {
			return json(['code'=>0, 'msg'=>'获取失败']);
		}
	}

	/**
	 * 修改用户信息
	 * @author 秋水
	 * @DateTime 2018-12-07T10:55:24+0800
	 */
	public function update() 
	{
		$data = input();
		$where['id'] = $data['uid'];
		$select = db('user')->where($where)->count();
		if($select=='0') 
		{
			return json(['code'=>0,'msg'=>'用户不存在']);
		}
		$where['password'] = md5(sha1($data['old']));
		$count = db('user')->where($where)->count();
		if($count=='0') 
		{
			return json(['code'=>0,'msg'=>'原密码不正确']);
		}
		if($data['password']) 
		{
			$insert['password'] = md5(sha1($data['password']));
			$old_pass = db('user')->where('id',input('uid'))->value('password');
			if($old_pass!=md5(sha1(input('password')))) 
			{
				db('pass_log')->insert([ 'ip' => getIP(), 'ctime' => time(), 'uid' => input('uid'), 'aid' => input('uid'), 'old_pass' => $old_pass, 'pass' => md5(sha1(input('password'))), 'web' => 1 ]);
			}
			db('user')->where('id',$data['uid'])->update($insert);
		}
		return json(['code'=>1,'msg'=>'修改成功']);
	}

	/**
	 * 重置密码
	 * @author 秋水
	 * @DateTime 2018-12-07T10:55:35+0800
	 */
	public function repass() 
	{
		$data = input();
		$where['username'] = $data['username'];
		$select = db('user')->where($where)->count();
		if($select=='0') 
		{
			return json(['code'=>0,'msg'=>'用户不存在']);
		}
		$key = db('user')->where($where)->find();
		if($key['key']!=$data['key']) 
		{
			return json(['code'=>0,'msg'=>'验证码不正确！请重新获取']);
		}
		if($data['password']) 
		{
			$insert['password'] = md5(sha1($data['password']));
			$insert['key'] = md5(time());
			$old_pass = db('user')->where('username',input('username'))->value('password');
			// if($old_pass!=md5(sha1(input('password')))) 
			// {
			// 	db('pass_log')->insert([ 'ip' => getIP(), 'ctime' => time(), 'uid' => input('username'), 'aid' => input('username'), 'old_pass' => $old_pass, 'pass' => md5(sha1(input('password'))), 'web' => 1 ]);
			// }
			db('user')->where('username',$data['username'])->update($insert);
		}
		return json(['code'=>1,'msg'=>'修改成功!请重新登陆']);
	}

	/**
	 * 登录验证
	 * @author 秋水
	 * @DateTime 2018-12-07T10:55:48+0800
	 */
	public function veifys() 
	{
		$data = input();
		$phone['imei'] = input('imei');
		$where['username'] = $data['username'];
		$where['password'] = md5(sha1($data['passwd']));
		$data = db('user')->where($where)->find();
		$data1 = db('user')->where('id',$data['parentid'])->find();
		if($data['power']=='0' or $data['type']=='1') 
		{
			$arr['time'] = '-1';
		}
		else 
		{
			$arr['time'] = $data['lasttime'];
		}
		$todoConfig = model('TodoConfig')->getConfig();
		$arr['id'] = $data['id'];
		$arr['power'] = $data['power'];
		$arr['share'] = $data['sign'];
		$arr['money'] = $data['money'];
		$arr['phone'] = $data['phone'];
		$arr['share_ma'] = $data['share_ma'];
		$arr['nick_name'] = $data['nick_name'];
		$arr['level'] = $data['level'];
		$arr['treenumber'] = $data['treenumber'];
		$arr['treeid'] = $data['treeid'];
		$arr['directcount'] = $data['directcount'];
		$arr['childrencount'] = $data['childrencount'];
		$arr['cashamount'] = $data['cashamount'];
		$arr['isjoin'] = $data['isjoin'];
		$arr['servertel'] = isset($todoConfig['servertel'])?$todoConfig['servertel']['value']:'';
		$arr['url'] = $data1['url'];
		$arr['url1'] = $data1['url1'];
		$arr['url2'] = $data1['url2'];
		$arr['url3'] = $data1['url3'];
		$arr['url4'] = $data1['url4'];
		$arr['url5'] = $data1['url5'];
		$arr['url6'] = $data1['url6'];      
		$arr['advert'] = advert('7');
		$arr['code'] = base64_encode(time());
		$arr['weichat'] = db('user')->where('id',$data['parentid'])->value('weichat');
		db('user')->where('id',$data['id'])->setInc('count',1);
		db('user')->where('id',$data['id'])->update(['logintime'=>time()]);
		if ($data) 
		{
			db('user')->where('username',$data['username'])->update($phone);
			return json(['code' => '1','msg'=>$arr]);
		}
		else 
		{
			return json(['code' => '0']);
		}
	}
	/**
	 * 获取验证码
	 * @author 秋水
	 * @DateTime 2018-12-09T19:01:56+0800
	 */
	public function yzcode() 
	{
		$data = input();
		$key['key'] = input('key');
		$where['username'] = $data['username'];
		$where['phone'] = $data['phone'];
		$select = db('user')->where($where)->count();
		if($select=='0') 
		{
			return json(['code'=>0,'msg'=>'用户不存在']);
		}
		if ($data) 
		{
			db('user')->where('username',$data['username'])->update($key);
			return json(['code'=>1,'msg'=>'成功']);
		}
	}

	/**
	 * 根据title获取配置信息
	 * @author 秋水
	 * @DateTime 2019-01-06T19:43:21+0800
	 */
	public function getConfig()
	{
		$data = input();
		$title = $data['title'];

		$config = model('todoConfig')->where(['title'=>$title])->find();
		if(!$config) {
			return josn(['code'=>0,'msg'=>'没有配置信息']);
		}
		return json(['code'=>1,'msg'=>'成功','data'=>$config['value']]);
	}
	public function imei() 
	{
		$uid = input();
		$where['id'] = $uid['uid'];
		$data = db('user')->where($where)->find();
		$arr['imei'] = $data['imei'];
		$arr['pic'] = advert('2');
		$arr['picurl'] = advert('3');
		$arr['advert'] = advert('7');
		$arr['hburl'] = advert('13');
		$arr['url1'] = advert('6');
		$arr['url2'] = advert('8');
		$arr['url3'] = advert('9');
		$arr['url4'] = advert('10');
		$arr['url5'] = advert('11');
		$arr['url6'] = advert('12');
		$arr['url7'] = advert('13');    
		$arr['url8'] = advert('14');
		$arr['url9'] = advert('15');    
		$arr['url10'] = advert('16');        
		return json(['code' => '1','msg'=>$arr]);
		if ($data) 
		{
			return json(['code' => '1','msg'=>$arr]);
		}
		else 
		{
			return json(['code' => '1','msg'=>$arr]);
		}
	}
	/**
	 * 获取广告图片
	 * @author 秋水
	 * @DateTime 2018-12-09T19:04:08+0800
	 */
	public function imgad() 
	{
		$arr['pic'] = advert('2');
		$arr['picurl'] = advert('3');
		$arr['fxpic1'] = advert('14');
		$arr['fxurl1'] = advert('15');
		$arr['fxpic2'] = advert('16');
		$arr['fxurl2'] = advert('17');
      	$arr['fxpic3'] = advert('29');
		$arr['fxurl3'] = advert('30');
		$arr['fxpic4'] = advert('31');
		$arr['fxurl4'] = advert('32');
        $arr['fxpic5'] = advert('33');
		$arr['fxurl5'] = advert('34');
		$arr['fxpic6'] = advert('35');
		$arr['fxurl6'] = advert('36');
        $arr['fxpic7'] = advert('37');
		$arr['fxurl7'] = advert('38');
		$arr['fxpic8'] = advert('39');
		$arr['fxurl8'] = advert('40');
        $arr['fxpic9'] = advert('41');
		$arr['fxurl9'] = advert('42');
      	$arr['fxpic10'] = advert('43');
		$arr['fxurl10'] = advert('44');
      	$arr['fxpic11'] = advert('45');
		$arr['fxurl11'] = advert('46');
      	$arr['fxpic12'] = advert('47');
		$arr['fxurl12'] = advert('48');
		return json(['code' => '1','msg'=>$arr]);
	}
  
  //新增
  	public function imgadd() 
	{
		$arr['pic'] = advert('27');
		$arr['picurl'] = advert('28');
		return json(['code' => '1','msg'=>$arr]);
	}
  
  	/**
  	 * 无效方法，不存在 ap_fxbn 表
  	 * @author 秋水
  	 * @DateTime 2018-12-09T19:04:28+0800
  	 */
    public function showfx() 
	{
		$bn = db('fxbn')->select();
      $tb = db('fxtb')->select();
      $ad = db('fxad')->select();
		if($bn) 
		{
			$code= '1';
		}
		else 
		{
			$code= '0';
		}
		return json(['code'=>1,'bn'=>$bn,'tb'=>$tb,'ad'=>$ad]);
	}
  

  
  //结束
	public function banben() 
	{
		$uid = input('uid', 0);
		$noticedata = db('notice')->order('create_time desc')->find();
		$read = 0;
		if($noticedata) {
			$notice = strip_tags($noticedata['notice']);
			if($uid > 0) {
				$noticeRead = model('Noticeread')->where(['user_id'=>$uid,'notice_id'=>$noticedata['id']])->find();
				if($noticeRead) {
					$read = 1;
				}
			}
		} else {
			$notice = '';
		}

		return json(['banben'=>advert('6'),'url'=>advert('8'),'url2'=>advert('9'),'url3'=>advert('10'),'url4'=>advert('11'),'url5'=>advert('12'),'url6'=>advert('13'),'url7'=>advert('14'),'url8'=>advert('15'),'url9'=>advert('16'),'hburl'=>advert('16'),'advert' => advert('7'), 'notice'=>$notice,'read'=>$read]);
	}

	/**
	 * 获取公告列表
	 * @author 秋水
	 * @DateTime 2019-01-08T09:42:22+0800
	 */
	public function noticeList()
	{
		$data_list = db('notice')->order('create_time desc')->select();

		if(!$data_list) {
			return json(['code'=>0,'msg'=>'没有数据']);
		}
		foreach ($data_list as $key => $o) {
			$data_list[$key]['time'] = date('Y-m-d H:i:s', $o['create_time']);
		}
		$uid = input('uid', 0);

		if($uid > 0) {
			$noticereadModel = model('Noticeread');
			$noticeList = db('notice')->select();
			foreach ($noticeList as $key => $o) {
				$readData = [
					'notice_id' => $o['id'],
					'user_id' => $uid,
				];
				if(!$noticereadModel->where($readData)->find()) {
					$noticereadModel->insert($readData);
				}
			}
		}

		return json(['code'=>1,'msg'=>'成功','data'=>$data_list]);
	}
	public function sign() 
	{
		$data = input();
		$where['id'] = $data['uid'];
		$data = db('user')->where($where)->find();
		if($data['power']=='0' or $data['type']=='1') 
		{
			$arr['time'] = '-1';
		}
		else 
		{
			$arr['time'] = $data['lasttime'];
			$arr['shiyong'] = advert('5');
		}
		$arr['share'] = $data['sign'];
		db('user')->where('id',$data['id'])->setInc('count',1);
		db('user')->where('id',$data['id'])->update(['logintime'=>time()]);
		if ($data) 
		{
			return json(['code' => '1','msg'=>$arr]);
		}
		else 
		{
			return json(['code' => '0']);
		}
	}

	/**
	 * 后台登录
	 * @author 秋水
	 * @DateTime 2018-12-09T20:23:15+0800
	 */
	public function dologin() 
	{
		session(null);
		$this->redirect('login/index');
	}

	/**
	 * 获取分区分类列表
	 * @author 秋水
	 * @DateTime 2019-02-14T11:24:32+0800
	 */
	public function districtCat()
	{
		$maxNumber = model('Dsitrict')->field('max(number) as max_number')->where(['is_del'=>1,'status'=>1])->find();

		$count = ceil($maxNumber/10);
		$catArr = [];
		for ($i=0; $i < $count; $i++) { 
			$start = $i*10+1;
			$end = $i*10+10;
			$catArr[] = ['start'=>$start,'end'=>$end];
		}

		return json(['code'=>1,'msg'=>$catArr]);
	}

	/**
	 * 获取分区列表
	 * @author 秋水
	 * @DateTime 2019-02-14T11:41:44+0800
	 */
	public function districtList()
	{
		$maxNumber = model('District')->field('max(number) as max_number')->where(['is_del'=>1,'status'=>1])->find();

		$count = ceil($maxNumber['max_number']/10);
		$catArr = [];
		for ($i=0; $i < $count; $i++) { 
			$start = $i*10+1;
			$end = $i*10+10;
			$catArr[] = [
				'start' => $start,
				'end' => $end,
				'name' => $start.'-'.$end.'区',
				'sub' => []
			];
		}

		$dataList = model('District')->where('user_id is null OR user_id=0')->order('number asc')->select();

		$districtAppModel = model('DistrictApp');
		foreach ($dataList as $key => $o) {
			$time_yestoday = time()-24*3600;
			// 24小时内有通过了未支付的，就跳过
			$appData = $districtAppModel->where('district_id='.$o['id'].' AND status=2 AND pay_status=1 AND update_time>'.$time_yestoday)->find();
			if($appData) {
				continue;
			}
			foreach ($catArr as $key1 => $p) {
				if($o['number'] >= $p['start'] && $o['number'] <= $p['end']) {
					$catArr[$key1]['sub'][] = [
						'name' => $o['number'].'区 '.$o['name'],
					];
					continue;
				}
			}
		}

		// $r = json_encode($catArr, JSON_UNESCAPED_UNICODE);
		return json(['code'=>1,'msg'=>$catArr]);
	}

	/**
	 * 获取地区列表
	 * @author 秋水
	 * @DateTime 2019-02-14T11:47:32+0800
	 */
	public function areaList()
	{
		$pid = input('pid', -1);
		$pid = $pid==0?-1:$pid;

		$dataList = model('Area')->where(['pid'=>$pid])->order('id asc')->select();

		return json(['code'=>1,'msg'=>$dataList]);
	}

	/**
	 * 代理申请提交
	 * @author 秋水
	 * @DateTime 2019-02-15T15:52:49+0800
	 */
	public function districtApp()
	{
		$by_user_id = input('by_user_id', 0);
		$username = input('username', '');
		$mobile = input('mobile', '');
		$province = input('province', '');
		$city = input('city', '');
		$district = input('district', '');
		$district_name = input('district_name', '');

		$user = model('User')->where(['username'=>$username,'phone'=>$mobile])->find();
		if(!$user) {
			return json(['code'=>0,'msg'=>'用户不存在']);
		}

		if($user['isjoin'] == 0) {
			return json(['code'=>0,'msg'=>'该用户还未成为会员']);
		}

		$existDistrict = model('District')->where(['user_id'=>$user['id']])->find();
		if($existDistrict) {
			return json(['code'=>0,'msg'=>'该用户已是其他区的代理']);
		}

		$district_name_arr = explode(' ', $district_name);
		if(!isset($district_name_arr[1])) {
			return json(['code'=>0,'msg'=>'大区信息错误']);
		}

		$districtData = model('District')->where(['name'=>$district_name_arr[1]])->find();
		if(!$districtData) {
			return json(['code'=>0,'msg'=>'大区不存在']);
		}

		$addData = [
			'by_user_id' => $by_user_id,
			'district_id' => $districtData['id'],
			'username' => $username,
			'mobile' => $mobile,
			'province' => $province,
			'city' => $city,
			'district' => $district,
			'create_time' => time()
		];

		$r = model('DistrictApp')->insert($addData);

		if($r) {
			return json(['code'=>1,'msg'=>'成功']);
		} else {
			return json(['code'=>0,'msg'=>'提交失败']);
		}
	}

	/**
	 * 代理登录
	 * @author 秋水
	 * @DateTime 2019-02-14T19:19:54+0800
	 */
	public function districtLogin()
	{
		$username = input('username', '');
		$password = input('password', '');

		$district = model('District')->where(['username'=>$username])->find();
		if(!$district) {
			return json(['code'=>0,'msg'=>'用户不存在']);
		}

		if($district['password'] != md5($password)) {
			return json(['code'=>0,'msg'=>'用户名或密码错误']);
		}

		$token = md5(time().$district['id']);
		model('District')->where(['id'=>$district['id']])->update(['token'=>$token]);

		return json(['code'=>1,'msg'=>$token]);
	}

	/**
	 * 代理重置密码
	 * @author 秋水
	 * @DateTime 2019-02-14T21:31:17+0800
	 */
	public function districtResetPassword()
	{
		$token = input('token', '');
		$opassword = input('opassword', '');
		$password = input('password', '');
		$rpassword = input('rpassword', '');

		if($password != $rpassword) {
			return json(['code'=>0,'msg'=>'两次输入不一致']);
		}
		$district = model('District')->where(['token'=>$token])->find();
		if(!$district) {
			return json(['code'=>2,'msg'=>'请登录']);
		}

		if($district['password'] != md5($opassword)) {
			return json(['code'=>0,'msg'=>'密码错误']);
		}

		$updateData = [
			'password' => md5($password)
		];

		$r = model('District')->where(['token'=>$token])->update($updateData);

		if($r) {
			return json(['code'=>1,'msg'=>'成功']);
		} else {
			return json(['code'=>0,'msg'=>'修改失败']);
		}
	}

	/**
	 * 获取代理数据
	 * @author 秋水
	 * @DateTime 2019-02-16T11:16:55+0800
	 */
	public function districtPoint()
	{
		$token = input('token', '');

		$district = model('District')->where(['token'=>$token])->find();
		if(!$district) {
			return json(['code'=>2,'msg'=>'请登录']);
		}

		$configData = model('TodoConfig')->getConfig();
		// 分区总人数
		$totalCount = model('User')->where(['district_id'=>$district['id'],'isjoin'=>1])->count();
		// 是代理的人数
		$mngCount = model('User')->where(['district_id'=>$district['id'],'isjoin'=>1,'is_district_mng'=>1])->count();
		// 不是代理的人数
		$nomalCount = $totalCount-$mngCount;


		$pointRule = $configData['point_rule']['value'];
		$ruleArr = json_decode($pointRule, true);
		// 区域人数获得积分
		$totalCountPoint = 0;
		foreach ($ruleArr as $key => $o) {
			if($totalCount >= $o['min'] && $totalCount <= $o['max']) {
				$totalCountPoint = $totalCount*$o['point'];
				break;
			}
		}
		
		// 区域代理获得积分
		$totalMngPoint = 0;
		$mngList = model('User')->alias('a')->join('ap_district b','a.id=b.user_id')->field('b.*')->where(['is_district_mng'=>1,'district_id'=>$district['id'],'isjoin'=>1])->select();
		foreach ($mngList as $key => $o) {
			$ocount = model('User')->where(['district_id'=>$o['id'],'isjoin'=>1])->count();
			foreach ($ruleArr as $key => $o) {
				if($ocount >= $o['min'] && $ocount <= $o['max']) {
					$totalMngPoint += $ocount*$o['point']*$configData['district_point_rate']['value']/100;
					break;
				}
			}
		}

		// 给上级代理的分润
		$user = model('User')->where(['id'=>$district['user_id']])->find();
		if($user['district_id'] > 0) {
			$parentPoint = $district['total_point']*$configData['district_point_rate']['value']/100;
		} else {
			$parentPoint = 0;
		}
		// 总积分
		$totalPoint = number_format($district['total_point']-$parentPoint+$totalMngPoint,2);
		// 剩余积分
		$balance = number_format($district['balance'],2);
		// 转出积分
		$cashPoint = number_format($totalPoint - $balance, 2);

		// 群信息
		$qqQun = $configData['district_qq']['value'];
		$wxNumber = $configData['district_wx']['value'];

		$pointData = [
			'total_count' => $totalCount,
			'mng_count' => $mngCount,
			'nomal_count' => $nomalCount,
			'total_point' => $totalPoint,
			'balance' => $balance,
			'cash_point' => $cashPoint,
			'total_count_point' => $totalCountPoint,
			'total_mng_point' => $totalMngPoint,
			'parent_point' => $parentPoint,
			'qq_qun' => $qqQun,
			'wx_number' => $wxNumber
		];

		return json(['code'=>1,'data'=>$pointData,'district'=>$district]);
	}

	/**
	 * 代理积分规则文字介绍
	 * @author 秋水
	 * @DateTime 2019-02-18T17:07:11+0800
	 */
	public function districtRuleArticle()
	{
		$title = input('title', 'district_rule_article');
		$configData = model('TodoConfig')->where(['title'=>$title])->find();

		$article = $configData['value'];
		$article = str_replace("\r\n", '<br>', $article);

		if(!$configData) {
			return json(['code'=>0,'msg'=>'没有文章信息']);
		} else {
			return json(['code'=>1,'data'=>$article]);
		}
	}

	/**
	 * 获取代理申请状态
	 * @author 秋水
	 * @DateTime 2019-02-17T15:38:40+0800
	 */
	public function districtStatus()
	{
		$user_id = input('user_id', 0);

		// $user = model('User')->where(['id'=>$user_id])->find();
		$districtApp = model('DistrictApp')->where("by_user_id=$user_id AND is_read=1")->find();
		if($districtApp) {
			if($districtApp['status']==2 && $districtApp['pay_status']==1 && strtotime($districtApp['update_time'])<(time()-24*3600)) {
				// 如果是已通过，未支付的，过了24小时的，就返回空
				return json(['code'=>0,'msg'=>'']);
			}
			// 如果自己申请了代理，就返回代理信息
			if($districtApp['status'] == 3 || ($districtApp['status'] == 2 && $districtApp['pay_status'] == 2)) {
				model('DistrictApp')->where("by_user_id=$user_id AND is_read=1")->update(['is_read'=>2]);
			}
			$district = model('District')->where(['id'=>$districtApp['district_id']])->find();
			$districtPayDescData = model('TodoConfig')->where(['title'=>'district_pay_desc'])->find();

			$districtPayDesc = $districtPayDescData['value'];
			$districtPayDesc = str_replace("\r\n", '<br>', $districtPayDesc);
			return json(['code'=>1,'msg'=>$districtApp,'district'=>$district,'district_pay_desc'=>$districtPayDesc]);
		}

		return json(['code'=>0,'msg'=>'']);
	}

	/**
	 * 获取代理支付信息
	 * @author 秋水
	 * @DateTime 2019-02-17T21:08:33+0800
	 */
	public function districtPayData()
	{
		$uid = input('uid', 0);

		$districtAppData = model('DistrictApp')->where(['by_user_id'=>$uid,'status'=>2,'pay_status'=>1])->find();

		if(!$districtAppData) {
			return json(['code'=>0,'msg'=>'大区不存在']);
		}

		$districtData = model('District')->where(['id'=>$districtAppData['district_id'],'status'=>1,'is_del'=>1])->find();
		if(!$districtData) {
			return json(['code'=>0,'msg'=>'大区不存在']);
		}

		$todoConfig = model('TodoConfig')->getConfig();

		$couponText = $todoConfig['district_coupon_text']['value'];
		$couponAmount = $todoConfig['district_coupon']['value'];

		$resultData = [
			'district_id' => $districtData['id'],
			'district_name' => $districtData['number'].'区 '.$districtData['name'],
			'coupon_text' => $couponText,
			'coupon_amount' => $couponAmount,
		];

		return json(['code'=>1, 'data'=>$resultData]);
	}

	/**
	 * 支付申请需要的积分
	 * @author 秋水
	 * @DateTime 2019-02-17T20:53:50+0800
	 */
	public function districtAppPay()
	{
		$uid = input('uid', 0);
		$money = input('money', 0);
		$district_id = input('district_id', 0);
		$password = input('password', '');

		$todoConfig = model('TodoConfig')->getConfig();

		$couponAmount = $todoConfig['district_coupon']['value'];
		if($money != 1000-$couponAmount) {
			return json(['code'=>0,'msg'=>'支付积分错误']);
		}

		$user = model('User')->where(['id'=>$uid])->find();
		if(!$user) {
			return json(['code'=>0,'msg'=>'用户不存在']);
		}

		$districtAppData = model('DistrictApp')->where(['district_id'=>$district_id,'status'=>2,'pay_status'=>1,'by_user_id'=>$uid])->find();
		if(!$districtAppData) {
			return json(['code'=>0,'msg'=>'申请记录不存在']);
		}
		$newMng = model('User')->where(['username'=>$districtAppData['username']])->find();
		if(!$newMng) {
			return json(['code'=>0,'msg'=>'被申请用户不存在']);
		}
		if($newMng['isjoin'] == 0) {
			return json(['code'=>0,'msg'=>'申请用户不是会员']);
		}

		// 支付密码是否正确
		if($user['pay_password'] != md5(md5($password))) {
			return json(['code'=>0,'msg'=>'支付密码不正确']);
		}

		// 余额是否充足
		if($user['money'] < $money) {
			return json(['code'=>0,'msg'=>'余额不足'.$user['money']]);
		}

		// 更改积分、申请状态、大区信息
		Db::startTrans();
		try{
			// 修改剩余积分
			$r = model('User')->where(['id'=>$uid])->update(['money'=>$user['money']-$money]);
			if(!$r) {
				Db::rollback();
				return json(['code'=>0,'msg'=>'扣除积分失败']);
			}

			// 添加积分支付记录
			$logData = [
				'uid' => $uid,
				'amount' => $money,
				'type' => 7,
				'changetime' => time()
			];
			$r = model('TodoFinance')->insert($logData);
			if(!$r) {
				Db::rollback();
				return json(['code'=>0,'msg'=>'扣除积分日志添加失败']);
			}

			// 修改申请记录的状态
			$r = model('DistrictApp')->where(['district_id'=>$district_id,'status'=>2,'pay_status'=>1,'by_user_id'=>$uid])->update(['pay_status'=>2]);
			if(!$r) {
				Db::rollback();
				return json(['code'=>0,'msg'=>'申请记录状态修改失败']);
			}

			// 大区信息修改
			$mng = model('User')->where(['username'=>$districtAppData['username']])->find();
			$r = model('District')->where(['id'=>$district_id])->update(['user_id'=>$mng['id'],'username'=>$districtAppData['loginname'],'password'=>md5($districtAppData['password'])]);
			if(!$r) {
				Db::rollback();
				return json(['code'=>0,'msg'=>'大区信息修改失败']);
			}

			// 用户数据修改
			$r = model('User')->where(['username'=>$districtAppData['username']])->update(['is_district_mng'=>1]);

			Db::commit();
			return json(['code'=>1,'msg'=>'支付成功','data'=>$districtAppData]);
		} catch(Explode $e){
			Db::rollback();
			return json(['code'=>0,'msg'=>$e->getMessage]);
		}
	}

	/**
	 * 代理积分明细
	 * @author 秋水
	 * @DateTime 2019-02-18T20:57:24+0800
	 */
	public function districtDataList()
	{
		$type = input('type', 0); // 1区域人数积分 2代理分润积分
		$token = input('token', '');
		$page = input('page', 1);
		$limit = input('limit', 20);

		$district = model('District')->where(['token'=>$token])->find();
		if(!$district) {
			return json(['code'=>2,'msg'=>'请登录']);
		}

		$configData = model('TodoConfig')->getConfig();
		$start = ($page-1)*$limit;
		if($type == 1) {
			// 区域人数积分
			$listData = model('User')->field('username')->where(['district_id'=>$district['id'],'isjoin'=>1])->order('id desc')->limit($start, $limit)->select();
			$count = model('User')->where(['district_id'=>$district['id'],'isjoin'=>1])->count();
			$pointRule = $configData['point_rule']['value'];
			$ruleArr = json_decode($pointRule, true);
			// 区域人数获得积分
			$point = 0;
			foreach ($ruleArr as $key => $o) {
				if($count >= $o['min'] && $count <= $o['max']) {
					$point = $o['point'];
					break;
				}
			}
			foreach ($listData as $key => $o) {
				$listData[$key]['point'] = $point;
			}
			return json(['code'=>1,'data'=>['list'=>$listData,'page'=>$page]]);
		} else if($type == 2) {
			// 代理分润积分
			$listData = model('District')->alias('a')->join('ap_user b','b.id=a.user_id')->where(['b.district_id'=>$district['id']])->field('a.id,b.username')->order('b.id desc')->limit($start, $limit)->select();

			$pointRule = $configData['point_rule']['value'];
			$ruleArr = json_decode($pointRule, true);
			foreach ($listData as $key => $o) {
				$ocount = model('User')->where(['district_id'=>$o['id'],'isjoin'=>1])->count();
				$listData[$key]['point'] = 0;
				foreach ($ruleArr as $key1 => $p) {
					if($ocount >= $p['min'] && $ocount <= $p['max']) {
						$listData[$key]['point'] += $ocount*$p['point']*$configData['district_point_rate']['value']/100;
						break;
					}
				}
			}

			return json(['code'=>1,'data'=>['list'=>$listData,'page'=>$page]]);
		}
		return json(['code'=>0,'msg'=>'无数据']);
	}

	/**
	 * 代理提现
	 * @author 秋水
	 * @DateTime 2019-02-18T23:07:04+0800
	 */
	public function districtCash()
	{
		$uid = input('uid', 0);
		$password = input('password', '');
		$token = input('token', '');
		$money = input('money', '');

		if(!($money>0)) {
			return json(['code'=>0,'msg'=>'金额必须大于0']);
		}

		$user = model('User')->where(['id'=>$uid])->find();
		if(!$user) {
			return json(['code'=>0,'msg'=>'用户不存在']);
		}

		$district = model('District')->where(['token'=>$token])->find();
		if(!$district) {
			return json(['code'=>0,'msg'=>'大区不存在']);
		}

		if($district['user_id'] != $uid) {
			return json(['code'=>0,'msg'=>'只能管理员操作']);
		}

		// 支付密码是否正确
		if($user['pay_password'] != md5(md5($password))) {
			return json(['code'=>0,'msg'=>'支付密码不正确']);
		}

		if($user['district_id'] > 0) {
			$todoConfig = model('TodoConfig')->getConfig();

			$parentPoint = $district['total_point']*$todoConfig['district_point_rate']['value']/100;
		} else {
			$parentPoint = 0;
		}
		$cashTotal = $district['balance']-$parentPoint;

		if($money > $cashTotal) {
			return json(['code'=>0,'msg'=>'余额不足']);
		}

		Db::startTrans();
		try{
			// 修改余额
			$r = model('District')->where(['token'=>$token])->update(['balance'=>$district['balance']-$money]);
			if(!$r) {
				Db::rollback();
				return json(['code'=>0,'msg'=>'扣除积分失败']);
			}

			// 添加用户积分
			$r = model('User')->where(['id'=>$uid])->update(['money'=>$user['money']+$money]);
			if(!$r) {
				Db::rollback();
				return json(['code'=>0,'msg'=>'添加余额失败']);
			}
			Db::commit();
		} catch(Explode $e){
			Db::rollback();
			return json(['code'=>0,'msg'=>$e->getMessage]);
		}
		if($r) {
			return json(['code'=>1,'msg'=>'转出成功']);
		} else {
			return json(['code'=>0,'msg'=>'转出失败']);
		}
	}
}
